<template>
	<div>
		<ProTable ref="proTable" title="开票管理" :columns="columns" :requestApi="getTableList" :init-param="initParam">
			<!-- 表格 功能 按钮 -->
			<template #otherButton>
				<el-button @click="onExport" v-auth="'finance:invoice:management:export:invoke'"> 导出 </el-button>
			</template>
			<!-- 表单 头部 数据 -->
			<template #tableHeader>
				<el-tabs v-model="activeTag" class="demo-tabs" @tab-click="handleTab">
					<el-tab-pane v-for="item in tags" :key="item.name" :label="`${item.label}(${item.data})`" :name="item.name"></el-tab-pane>
				</el-tabs>
			</template>
			<!-- Expand -->
			<template #expand="scope">
				{{ scope.row }}
			</template>

			<!-- 表格操作 -->
			<template #operation="{ row }">
				<el-button
					type="primary"
					link
					v-if="[1].includes(row.invoiceStatus)"
					v-auth="'finance:invoice:management:download:invoke'"
					@click="onAudit(row)"
				>
					下载发票
				</el-button>
			</template>
		</ProTable>
		<Audit :visible="auditVisible" :row="auditRow" @handleClose="closeAudit"></Audit>
	</div>
</template>

<script setup lang="tsx" name="financeInvoice">
import { onMounted, ref, reactive, computed, nextTick } from 'vue';
import dayjs from 'dayjs';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { NextLoading } from '/@/utils/loading';
import ProTable from '../../../../components/ProTable/index.vue';
import { ProTableInstance, ColumnProps } from '../../../../components/ProTable/interface';
import { fetchInvoiceStatics, fetchInvoiceList, fetchInvoiceExport } from '/@/api/finance';
import Audit from './dialog/audit.vue';
import { fenToYuan } from '/@/utils/commonFunction';
import { useDownload } from '/@/hooks/useDownload';

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

const router = useRouter();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	searchType: 'ORDER-NO',
	timeType: 'APPLY',
});

const activeTag = ref<any>('');
const tags = ref<any>([
	{
		label: '全部发票',
		name: '',
		data: 0,
	},
	{
		label: '待开票',
		name: '0',
		data: 0,
	},
	{
		label: '已开票',
		name: '1',
		data: 0,
	},
	{
		label: '已作废',
		name: '-1',
		data: 0,
	},
]);

const handleTab = () => {
	nextTick(() => {
		proTable.value?.getTableList();
	});
};

const initStatics = async (params: any) => {
	const { code, data } = await fetchInvoiceStatics(params);
	if (code == 200) {
		tags.value = [
			{
				label: '全部发票',
				name: '',
				data: data.totalCount,
			},
			{
				label: '待开票',
				name: '0',
				data: data.pendingCount,
			},
			{
				label: '已开票',
				name: '1',
				data: data.finishCount,
			},
			{
				label: '已作废',
				name: '-1',
				data: data.cancelCount,
			},
		];
	}
};

const handleParams = (params: any) => {
	let data = {
		...params,
	};
	if (activeTag.value) {
		data.invoiceStatus = activeTag.value;
	}
	if (data.paramTime) {
		data.startTime = dayjs(data.paramTime[0]).format('YYYY-MM-DD HH:mm:ss');
		data.endTime = dayjs(data.paramTime[1]).format('YYYY-MM-DD HH:mm:ss');
		delete data.paramTimeType;
		delete data.paramTime;
	}
	return data;
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getTableList"
const getTableList = (params: any) => {
	let data = handleParams(params);

	initStatics(data);
	return fetchInvoiceList(data);
};

const searchArr = [
	{
		label: '订单编号',
		value: 'ORDER-NO',
	},
];

// 表格配置项
const columns: ColumnProps<any>[] = [
	{
		prop: 'keywords',
		label: '订单搜索',
		isShow: false,
		search: {
			span: 2,
			render: (scope: any) => {
				const slot = {
					prepend: () => (
						<el-select
							v-model={scope.searchParam.searchType}
							placeholder="Select"
							style="width: 100px"
							onChange={(value) => (scope.searchParam.searchType = value)}
						>
							{searchArr.map((item) => (
								<el-option key={item.value} label={item.label} value={item.value} />
							))}
						</el-select>
					),
				};
				return <el-input v-model={scope.modelValue} v-slots={slot} placeholder={getPlaceholder.value} maxlength={50}></el-input>;
			},
		},
	},
	{
		prop: 'paramTime',
		label: '发票时间',
		isShow: false,
		search: {
			span: 2,
			xs: 1,
			sm: 1,
			md: 2,
			lg: 1,
			xl: 1,
			render: (scope: any) => {
				return (
					<div class="flex-center">
						<el-select
							v-model={scope.searchParam.timeType}
							placeholder="Select"
							style="width: 100px"
							class="mini-gray-select flex-shrink"
							onChange={(value) => (scope.searchParam.timeType = value)}
						>
							{[
								{
									label: '申请时间',
									value: 'APPLY',
								},
								{
									label: '开票时间',
									value: 'EXECUTE',
								},
							].map((item) => (
								<el-option key={item.value} label={item.label} value={item.value} />
							))}
						</el-select>
						<el-date-picker
							v-model={scope.searchParam.paramTime}
							type="datetimerange"
							start-placeholder="开始时间"
							end-placeholder="结束时间"
							format="YYYY-MM-DD HH:mm:ss"
							date-format="YYYY-MM-DD"
							time-format="HH:mm:ss"
						/>
					</div>
				);
			},
		},
	},
	{
		prop: 'orderNo',
		minWidth: 220,
		label: '订单编号',
		render: (scope) => {
			return (
				<el-link type="primary" underline={false} onClick={() => router.push(`/order/query/detail/${scope.row.orderId}`)}>
					{scope.row.orderNo}
				</el-link>
			);
		},
	},
	{
		prop: 'amount',
		label: '开票金额',
		minWidth: 160,
		render: (scope) => {
			return fenToYuan(scope.row.amount);
		},
	},
	{
		prop: 'type',
		minWidth: 120,
		label: '发票类型',
	},
	{
		prop: 'invoiceType',
		minWidth: 100,
		label: '抬头类型',
		enum: [
			{
				label: '个人',
				value: 0,
			},
			{
				label: '企业',
				value: 1,
			},
		],
	},
	{
		prop: 'invoiceHeader',
		minWidth: 100,
		label: '发票抬头',
	},
	{
		prop: 'creditCode',
		minWidth: 100,
		label: '税号',
	},
	{
		prop: 'registeredAddr',
		label: '注册地址',
		minWidth: 200,
	},
	{
		prop: 'fixedMobile',
		label: '注册电话',
		minWidth: 130,
	},
	{
		prop: 'bankName',
		label: '开户银行',
		minWidth: 120,
	},
	{
		prop: 'bankAcct',
		label: '银行账号',
		minWidth: 120,
	},
	{
		prop: 'receiveMobile',
		label: '收票人手机',
		minWidth: 120,
	},
	{
		prop: 'receiveEmail',
		label: '收票人邮箱',
		minWidth: 120,
	},
	{
		prop: 'invoiceStatus',
		label: '发票状态',
		minWidth: 120,
		enum: [
			{
				label: '待开票',
				value: 0,
			},
			{
				label: '已开票',
				value: 1,
			},
			{
				label: '已作废',
				value: -1,
			},
		],
	},
	{
		prop: 'createTime',
		label: '申请时间',
		minWidth: 160,
	},
	{ prop: 'operation', label: '操作', fixed: 'right', width: 100, align: 'left' },
];

const getPlaceholder = computed(() => {
	const target = searchArr.find((item) => {
		return item.value == proTable.value?.searchParam.searchType;
	});
	return target ? `输入${target?.label}搜索` : '';
});

const auditVisible = ref(false);
const auditRow = ref();

const onAudit = (row: any) => {
	const fetchInvoiceDown = (url: string) => {
		return fetch(url)
			.then((response) => response.blob())
			.then((blob) => blob);
	};
	useDownload(() => fetchInvoiceDown(row.invoiceUrl), '发票', {}, true, `.${row.invoiceUrl.split('.').pop()}`);
};

const closeAudit = (success: boolean) => {
	auditVisible.value = false;
	if (success) {
		proTable.value?.getTableList();
	}
};

// 保存并导出
const onExport = () => {
	ElMessageBox.confirm('确认导出数据?', '温馨提示', { type: 'warning' }).then(() =>
		useDownload(fetchInvoiceExport, '开票列表', handleParams(proTable.value?.searchParam))
	);
};
</script>

<style lang="scss">
.demo-tabs {
	.el-tabs__header {
		margin-bottom: 0;
	}
}
</style>
